﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace YJY_DMZS.Barcode
{
    public partial class FrmBarcodeCreate : XtraForm
    {
        public FrmBarcodeCreate()
        {
            InitializeComponent();
            InitGrid();
        }

        /// <summary>
        /// 网格数据源
        /// </summary>
        private DataTable dt;
        /// <summary>
        /// 条码风格符号
        /// </summary>
        private string Separator = "-";
        /// <summary>
        /// 产品
        /// </summary>
        private DMZS.Model.Product Product = null;

        private void FrmBarCodePrint_Load(object sender, EventArgs e)
        { 
            dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] {
                new DataColumn("ProductID"),
                new DataColumn("ProductCode"), 
                new DataColumn("ProductName"),
                new DataColumn("Model"),
                new DataColumn("Specification"),
                new DataColumn("Barcode") });

            grdBody.DataSource = dt;
            dteDate.DateTime = DateTime.Now.Date;
        }

        private void txtSerialNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')
            {
                e.KeyChar = '0';
            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (!ValidateProduct())
            {
                XtraMessageBox.Show("不存在该产品编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (Product == null)
            {
                return;
            }

            if (dt.Rows.Count != 0 && DialogResult.Cancel == XtraMessageBox.Show("将清空当前数据，是否继续?", Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                return;

            dt.Clear();

            for (int i = Convert.ToInt32(spnBeginNumber.Value); i < Convert.ToInt32(spnBeginNumber.Value) + Convert.ToInt32(spnCount.Value); i++)
            {
                DataRow row = dt.NewRow();
                row["ProductID"] = Product.ID;
                row["ProductCode"] = Product.Code;
                row["ProductName"] = Product.Name; 
                row["Model"] = Product.Model;
                row["Specification"] = Product.Specification;
                row["Barcode"] = bteProductCode.Text.Trim() + '-' + DateTime.Now.ToString(cbbData_info.Text) + '-' + i.ToString(txtSerialNumber.Text.Trim());
                dt.Rows.Add(row);
            }
        }

        private void bteProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmProduct_dlg frm = new DialogForm.FrmProduct_dlg();
            frm.MultiSelect = false;
            frm.ReturnList += new DialogForm.FrmProduct_dlg.ReturnListEventHandler(frm_ReturnList);
            frm.ShowDialog();
        }

        void frm_ReturnList(List<DataRow> list)
        {
            if (list == null || list.Count == 0) return;

            DMZS.BLL.Product bll = new DMZS.BLL.Product();
            Product = bll.GetModel(Convert.ToInt64(list[0]["ID"]));
            bteProductCode.Text = Product == null ? "" : Product.Code;
            txtProductName.Text = Product == null ? "" : Product.Name;
            SetBeginValue(bteProductCode.Text.Trim(), dteDate.DateTime.Date, cbbData_info.Text);
        }

        private void bteProductCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!ValidateProduct())
                {
                    XtraMessageBox.Show("不存在该产品编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bteProductCode.Focus();
                    bteProductCode.SelectAll();
                }
                else
                {
                    SendKeys.Send("{TAB}");
                }
            }
        }

        /// <summary>
        /// 验证产品输入
        /// </summary>
        /// <returns></returns>
        private bool ValidateProduct()
        {
            if (bteProductCode.Text.Length == 0)
            {
                Product = null;

                bteProductCode.Text = "";
                txtProductName.Text = "";
                spnBeginNumber.Value = 0;
                return true;
            }

            DMZS.BLL.Product bll = new DMZS.BLL.Product();
            Product = bll.GetModel(bteProductCode.Text.Trim());
            if (Product != null)
            {
                txtProductName.Text = Product.Name;
                SetBeginValue(bteProductCode.Text.Trim(), dteDate.DateTime.Date, cbbData_info.Text);
                return true;
            }
            else
            {
                txtProductName.Text = "";
                spnBeginNumber.Value = 0;
                return false;
            }
        }
        /// <summary>
        /// 产品条码编号流水号最小值
        /// </summary>
        /// <param name="ProductCode"></param>
        /// <param name="Date"></param>
        /// <returns></returns>
        private bool SetBeginValue(string ProductCode, DateTime Date, string Dateformat)
        {
            if (Product == null)
            {
                spnBeginNumber.Value = 0;
                return true;
            }

            DMZS.BLL.Common bll = new DMZS.BLL.Common();
            int result = bll.GetBeginBarcodeNumber(ProductCode, Date, Dateformat, Separator, txtSerialNumber.Text.Trim().Length);
            if (result != -1)
            {
                spnBeginNumber.Value = result;
                btnCreateUI.Enabled = true;
                return true;
            }
            else
            {
                btnCreateUI.Enabled = false;
                return false;
            }
        }

        private void dteDate_EditValueChanged(object sender, EventArgs e)
        {
            if (bteProductCode.Text.Trim().Length == 0) return;

            SetBeginValue(bteProductCode.Text.Trim(), dteDate.DateTime.Date, cbbData_info.Text);
        }

        private void cbbData_info_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bteProductCode.Text.Trim().Length == 0) return;

            SetBeginValue(bteProductCode.Text.Trim(), dteDate.DateTime.Date, cbbData_info.Text);
        }

        private void btnCreateDB_Click(object sender, EventArgs e)
        {
            if (grvBody.GetFocusedDataRow() == null) return;

            DMZS.BLL.Barcode bll = new DMZS.BLL.Barcode();
            DMZS.Model.Barcode model = new DMZS.Model.Barcode();

            bool success = true;
            foreach (DataRow row in (grdBody.DataSource as DataTable).Rows)
            {
                model.Code = row["Barcode"].ToString();
                model.ProductID = Convert.ToInt64(row["ProductID"]);
                model.CreateTime = DateTime.Now;
                model.Status = 0;
                model.PrintCount = 0;
                model.ReturnCount = 0;
                model.ParentID = 0;
                success = success && (bll.AddExpand(model) >= 0 ? true : false);
            }
            if (success)
            {
                XtraMessageBox.Show("导入成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("导入失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Count == 0) return;

            if (System.IO.File.Exists(Application.StartupPath + "\\frxFiles\\" + "产品条码模板.frx"))
            {
                FastReport.Report rpt = new FastReport.Report();
                rpt.Load(Application.StartupPath + "\\frxFiles\\" + "产品条码模板.frx");
                DataTable dtnew = dt.Copy();
                dt.Columns.Remove("ProductID");
                dt.AcceptChanges();
                //dtnew.TableName = "条码信息";
                //dtnew.Columns["Barcode"].ColumnName = "条码";
                //dtnew.Columns["ProductCode"].ColumnName = "产品编号";
                //dtnew.Columns["ProductName"].ColumnName = "产品名称";
                //dtnew.Columns["Specification"].ColumnName = "规格";
                //dtnew.Columns["Model"].ColumnName = "型号";
                rpt.RegisterData(dtnew, "条码信息");
                rpt.Show(true);
                if (DialogResult.Yes == XtraMessageBox.Show("是否已打印？", "打印记录", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                {
                    UpdatePrintCount();
                }
            }
            else
            {
                XtraMessageBox.Show("未发现打印文件\"rptFiles\"产品条码模板.frx。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        /// <summary>
        /// 更新打印次数（次数非张数）
        /// </summary>
        private void UpdatePrintCount()
        {
            DMZS.BLL.Barcode bll = new DMZS.BLL.Barcode();
            foreach (DataRow row in dt.Rows)
            {
                bll.UpdatePrintCount(row["Barcode"].ToString());
            }
        }

        private void txtSerialNumber_TextChanged(object sender, EventArgs e)
        {
            SetBeginValue(bteProductCode.Text.Trim(), dteDate.DateTime.Date, cbbData_info.Text);
        }
        //设计唛头模板
        private void btnDesign_Click(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(Application.StartupPath + "\\frxFiles\\" + "唛头标签模板.frx"))
            {
                FastReport.Report rpt = new FastReport.Report();
                rpt.Load(Application.StartupPath + "\\frxFiles\\" + "唛头标签模板.frx");
                DataTable dtnew = dt.Clone();
                dtnew.Columns.Remove("ProductID");
                dtnew.AcceptChanges();
                rpt.RegisterData(dtnew, "条码信息");
                rpt.Design();
            }
            else
            {
                XtraMessageBox.Show("未发现打印文件\"rptFiles\"产品条码模板.frx。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }


        /// <summary>
        /// 初始网格显示
        /// </summary>
        private void InitGrid()
        {
            grvBody.IndicatorWidth = grvBody.IndicatorWidth == -1 ? 40 : grvBody.IndicatorWidth;
            grvBody.OptionsView.ShowIndicator = true;

            CommonControl.DxGridHelper.InitGridStyle(grvBody);
        }

        private void grvBody_DoubleClick(object sender, EventArgs e)
        {

        }

        private void grvBody_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CommonControl.DxGridHelper.DrawRowIndicator(sender, e);
        }

        //设计产品标签模板
        private void btnDesign_cp_Click(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(Application.StartupPath + "\\frxFiles\\" + "产品标签模板.frx"))
            {
                FastReport.Report rpt = new FastReport.Report();
                rpt.Load(Application.StartupPath + "\\frxFiles\\" + "产品标签模板.frx");
                DataTable dtnew = dt.Clone();
                dtnew.Columns.Remove("ProductID");
                dtnew.AcceptChanges();
                rpt.RegisterData(dtnew, "条码信息");
                rpt.Design();
            }
            else
            {
                XtraMessageBox.Show("未发现打印文件\"rptFiles\"产品条码模板.frx。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void btnPrint_cp_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Count == 0) return;

            if (System.IO.File.Exists(Application.StartupPath + "\\frxFiles\\" + "产品标签模板.frx"))
            {
                FastReport.Report rpt = new FastReport.Report();
                rpt.Load(Application.StartupPath + "\\frxFiles\\" + "产品标签模板.frx");
                DataTable dtnew = dt.Copy();
                dtnew.Columns.Remove("ProductID");
                dtnew.AcceptChanges();
                rpt.RegisterData(dtnew, "条码信息");
                rpt.Show(true);
                if (DialogResult.Yes == XtraMessageBox.Show("是否已打印？", "打印记录", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                {
                    UpdatePrintCount();
                }
            }
            else
            {
                XtraMessageBox.Show("未发现打印文件\"rptFiles\"产品条码模板.frx。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void btnPrint_mt_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Count == 0) return;

            if (System.IO.File.Exists(Application.StartupPath + "\\frxFiles\\" + "唛头标签模板.frx"))
            {
                FastReport.Report rpt = new FastReport.Report();
                rpt.Load(Application.StartupPath + "\\frxFiles\\" + "唛头标签模板.frx");
                DataTable dtnew = dt.Copy();
                dtnew.Columns.Remove("ProductID");
                dtnew.AcceptChanges();
                rpt.RegisterData(dtnew, "条码信息");
                rpt.Show(true);
                if (DialogResult.Yes == XtraMessageBox.Show("是否已打印？", "打印记录", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                {
                    UpdatePrintCount();
                }
            }
            else
            {
                XtraMessageBox.Show("未发现打印文件\"rptFiles\"产品条码模板.frx。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        
    }
}
